<template>
	<el-select v-model="state.queryParams.shopId" style="width: 15%; margin-bottom: 20px" @change="shopChange">
		<el-option v-for="item in state.shopList" :key="item.shopId" :label="item.name" :value="item.shopId"></el-option>
	</el-select>
	<el-upload
		action="#"
		:multiple="false"
		:show-file-list="false"
		:http-request="handleHttpUpload"
		:before-upload="beforeAvatarUpload"
		:on-success="handleSuccess"
		:on-error="handleError"
	>
		<el-button type="primary" v-auth="'upms:material:add'">
			<el-icon> <ele-Upload /> </el-icon>上传图片</el-button
		>
	</el-upload>
	<div class="material-main">
		<div class="category" v-loading="groupLoading">
			<el-tree
				ref="treeRef"
				:data="state.treeList"
				:props="defaultProps"
				class="category-tree"
				@current-change="currentChange"
				:highlight-current="true"
			/>
			<div class="footer">
				<el-popover :visible="visible" placement="top" :width="350">
					<div class="popover-input">
						<div style="padding: 0 10px">
							<el-input v-model="groupName" placeholder="请输入分组名称" />
						</div>
						<div class="flex">
							<el-button :loading="groupLoading" @click="addGroup">保存</el-button>
							<el-button :loading="groupLoading" @click="(visible = false), (groupName = '')">关闭</el-button>
						</div>
					</div>
					<template #reference>
						<el-button v-auth="'upms:materialgroup:add'" @click="visible = true"
							><el-icon> <ele-Plus /> </el-icon>添加分组</el-button
						>
					</template>
				</el-popover>
				<el-button v-auth="'upms:materialgroup:page'" @click="doGroup">管理分组</el-button>
			</div>
		</div>
		<div class="media-list" v-loading="loading">
			<h1 class="title">{{ groupTitle }}</h1>
			<div class="image-list">
				<div class="image-item" v-for="(item, index) in state.materialList" :key="index">
					<el-card>
						<div class="image-box">
							<el-image :preview-teleported="true" :src="item.url" :preview-src-list="[item.url]" fit="cover"></el-image>
						</div>
						<div class="image-title">{{ item.name }}</div>
						<div class="image-bar">
							<el-button link type="primary" v-auth="'upms:material:edit'" @click="edit(item)">编辑</el-button>

							<el-popover placement="bottom" :width="400" trigger="click" :content="item.url">
								<template #reference>
									<el-button link type="primary">链接</el-button>
								</template>
								<div class="popover-input">
									<el-input v-model="item.url" id="url" />
									<el-button type="primary" @click="copyText(item.url)">复制</el-button>
								</div>
							</el-popover>
							<el-button link type="danger" v-auth="'upms:material:del'" @click="del(item.id)">删除</el-button>
						</div>
					</el-card>
				</div>
			</div>
			<!-- 分页 -->
			<pagination
				v-model:total="state.page.total"
				v-model:currentPage="state.page.currentPage"
				v-model:pageSize="state.page.pageSize"
				@changePage="initPage"
				:page-sizes="[12, 24]"
			></pagination>
			<!-- 素材分组管理 -->
			<el-drawer width="60%" v-model="groupDrawer" direction="rtl">
				<template #header>
					<h4>分组管理</h4>
				</template>
				<template #default>
					<MaterialGroup ref="materialGroupRef" @initGroup="getGroup"></MaterialGroup>
				</template>
			</el-drawer>
		</div>
	</div>
</template>
<script lang="ts" setup>
import { defineAsyncComponent, ref, reactive } from 'vue';
import { getPage, editObj, delObj } from '/@/api/upms/material';
import { getList, addObj as addObjGroup } from '/@/api/upms/materialgroup';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps, UploadRequestOptions } from 'element-plus';
import commonFunction from '/@/utils/commonFunction';
import { uploadFile } from '/@/api/upms/upload';
import { getList as getShopList } from '/@/api/shop/shopinfo';

const MaterialGroup = defineAsyncComponent(() => import('/@/views/upms/materialgroup/index.vue'));
interface MaterialObj {
	id: string;
	name: string;
	url: string;
}
interface DataState {
	page: {
		total: number;
		currentPage: number;
		pageSize: number;
		ascs: any;
		descs: any;
	};
	queryParams: {
		groupId: string;
		shopId: string;
	};
	treeList: Array<any>;
	materialList: Array<MaterialObj>;
	shopList: Array<any>;
}
const state = reactive<DataState>({
	page: {
		total: 0,
		currentPage: 1,
		pageSize: 12,
		ascs: [],
		descs: 'create_time',
	},
	queryParams: {
		groupId: '',
		shopId: '-1',
	},
	treeList: [],
	materialList: [],
	shopList: [],
});
const loading = ref(false);
const groupLoading = ref(false);
const groupTitle = ref('');
const groupName = ref('');
const materialGroupRef = ref();
const groupDrawer = ref(false);
const visible = ref(false);

const defaultProps = {
	children: 'children',
	label: 'name',
	id: 'id',
};
/**
 * 文件上传
 */
const handleHttpUpload = async (options: UploadRequestOptions) => {
	let formData = new FormData();
	formData.append('file', options.file);
	formData.append('type', '1');
	formData.append('groupId', state.queryParams.groupId ? state.queryParams.groupId : '-1');
	formData.append('shopId', state.queryParams.shopId);

	await uploadFile(formData)
		.then(() => {})
		.catch((error) => {
			options.onError(error as any);
		});
};
/**
 * 素材分页列表
 */
const initPage = () => {
	loading.value = true;
	getPage({
		current: state.page.currentPage,
		size: state.page.pageSize,
		ascs: state.page.ascs,
		descs: state.page.descs,
		groupId: state.queryParams.groupId ? state.queryParams.groupId : '-1',
		shopId: state.queryParams.shopId,
	})
		.then((response: any) => {
			state.materialList = response.data.data.records;
			state.page.total = response.data.data.total;
			loading.value = false;
		})
		.catch(() => {
			loading.value = false;
		});
};

/**
 * 修改素材
 */
const edit = (row: any) => {
	ElMessageBox.prompt('请输入素材名称', '修改素材名称', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		inputValue: row.name,
	}).then(({ value }) => {
		editObj({ id: row.id, name: value }).then(() => {
			ElMessage.success('修改成功');
			initPage();
		});
	});
};
/**
 * 删除素材
 */
const del = (id: string) => {
	ElMessageBox.confirm('此操作将删除该素材，是否继续?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		delObj(id)
			.then(() => {
				ElMessage.success('删除成功');
				initPage();
			})
			.catch(() => {
				loading.value = false;
			});
	});
};
/**
 * 上传素材前事件
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
	if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
		ElMessage.error('Avatar picture must be JPG or png format!');
		return false;
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('Avatar picture size can not exceed 2MB!');
		return false;
	}
	return true;
};
/**
 * 上传成功事件
 */
const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
	ElMessage.success('上传成功');
	initPage();
};
/**
 * 上传失败事件
 */
const handleError: UploadProps['onError'] = (error) => {
	ElMessage.error(error + '');
};
/**
 * 素材分组列表查询
 */
const getGroup = () => {
	groupLoading.value = true;
	getList({ shopId: state.queryParams.shopId })
		.then((response: any) => {
			state.treeList = response.data.data;
			state.treeList.unshift({ id: '-1', name: '未分组' });
			groupTitle.value = groupTitle.value ? groupTitle.value : '未分组';
			groupLoading.value = false;
		})
		.catch(() => {
			groupLoading.value = false;
		});
};
/**
 * 切换分组
 */
const currentChange = (row: any) => {
	state.queryParams.groupId = row.id;
	groupTitle.value = row.name;
	initPage();
};
/**
 * 添加分组
 */
const addGroup = () => {
	groupLoading.value = true;
	var params = { name: groupName.value, shopId: state.queryParams.shopId };
	addObjGroup(params)
		.then(() => {
			getGroup();
			groupLoading.value = false;
			visible.value = false;
			groupName.value = '';
		})
		.catch(() => {
			groupLoading.value = false;
		});
};
const doGroup = () => {
	groupDrawer.value = true;
	materialGroupRef.value.initPage();
};
const shopChange = () => {
	getGroup();
	initPage();
};
const getShop = () => {
	getShopList({}).then((response) => {
		const list = response.data.data;
		const shop = {
			shopId: '-1',
			name: '商城素材',
		};
		list.unshift(shop);
		state.shopList = list;
		state.queryParams.shopId = list[0].shopId;
		getGroup();
		initPage();
	});
};
// 复制
const { copyText } = commonFunction();

getShop();
</script>
<style lang="scss" scoped>
.material-main {
	display: flex;
	min-height: 500px;
	height: calc(max(100vh - 300px, 500px));
	margin-top: 15px;
	.category {
		display: flex;
		flex-direction: column;
		flex: none;
		width: 240px;
		box-sizing: border-box;
		border: 1px solid #dcdee0;
		margin-right: -1px;
		overflow: hidden;
		.category-tree {
			padding: 20px;
		}
		.footer {
			position: absolute;
			bottom: 2px;
			width: 240px;
			box-sizing: border-box;
			text-align: center;
			padding: 12px 0;
			height: 56px;
			box-shadow: 0 -1px 4px 0 rgb(0 0 0 / 10%);
		}
	}
	.media-list {
		flex: auto;
		box-sizing: border-box;
		border: 1px solid #dcdee0;
		padding: 12px;
		overflow-y: auto;
		.title {
			font-size: 16px;
			line-height: 24px;
			font-weight: 700;
			color: #323233;
		}
	}
}
.image-list {
	display: flex;
	flex-wrap: wrap;
	overflow: hidden;
	.image-item {
		position: relative;
		width: 175px;
		margin: 6px;
		.image-box {
			box-sizing: content-box;
			position: relative;
			height: 0;
			width: 100%;
			padding-bottom: 100%;
			cursor: pointer;
			background-color: #f7f8fa;
			background-position: 50%;
			background-size: cover;
			background-repeat: no-repeat;
			overflow: hidden;
		}
		.image-title {
			margin: 8px 0 4px;
			font-size: 14px;
			line-height: 20px;
			height: 20px;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
		}
		.image-bar {
			font-size: 0;
			height: 20px;
			button {
				margin-left: 0;
				padding: 0 3px;
			}
		}
	}
}
.popover-input {
	display: flex;
	justify-content: space-between;
}
</style>
